package com.wjjun.databinding;

import android.databinding.BindingAdapter;
import android.text.TextUtils;
import android.webkit.WebView;

import com.wjjun.customview.views.MyWebView;

/**
 * MyWebViewAdapter
 */
public class MyWebViewAdapter {

    @BindingAdapter(value = "url")
    public static void setUrl(WebView webView, String url) {
        webView.loadUrl(url);
    }


    @BindingAdapter(value = "html")
    public static void setHtml(MyWebView webView, String html) {
        webView.loadData(encode(html), "text/html", "utf-8");
    }

    @BindingAdapter(value = "canLoadUrl")
    public static void setLoadUrlAble(MyWebView webView, boolean canLoadUrl) {
        webView.setCanLoadUrl(canLoadUrl);
    }

    static final String digits = "0123456789ABCDEF";

    public static String encode(String s) {
        if (TextUtils.isEmpty(s)) {
            return "";
        }
        StringBuilder buf = new StringBuilder(s.length() + 16);
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
                    || (ch >= '0' && ch <= '9') || ".-*_".indexOf(ch) > -1) { //$NON-NLS-1$
                buf.append(ch);
            } else {
                byte[] bytes = new String(new char[]{ch}).getBytes();
                for (int j = 0; j < bytes.length; j++) {
                    buf.append('%');
                    buf.append(digits.charAt((bytes[j] & 0xf0) >> 4));
                    buf.append(digits.charAt(bytes[j] & 0xf));
                }
            }
        }
        return buf.toString();
    }


}
